package cn.mybatishelper.parser.jdbc;

import cn.mybatishelper.common.JdbcUtil;
import cn.mybatishelper.entity.database.DatabaseEntity;
import cn.mybatishelper.entity.vo.TableToMybatisVo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 连接数据库，并将取出的数据转化为所需业务类的解析器
 * postgresQL定制解析器
 *
 * @author yao
 */
public class PostgresqlJdbcParser extends AbstractJdbcParser {
    private static final Logger LOGGER = LoggerFactory.getLogger(PostgresqlJdbcParser.class);

    public PostgresqlJdbcParser() {
    }

    public PostgresqlJdbcParser(String addressUrl, String userName, String password, String schemaName) {
        super(addressUrl, password, schemaName, userName);
    }

    /**
     * 通过表名和过滤名获取数据库表实体集合
     */
    @Override
    public List<DatabaseEntity> getJdbcEntitys(List<TableToMybatisVo> vos) {
        if (!validateParser()) {
            LOGGER.error("数据解析器信息校验错误，无法提取表相关信息，解析中止...");
            return Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(vos)) {
            LOGGER.error("传入的待解析表信息为空，解析中止...");
            return Collections.emptyList();
        }
        List<DatabaseEntity> entityList = new ArrayList<DatabaseEntity>();
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(this.addressUrl, this.userName, this.password);
            DatabaseMetaData metaData = connection.getMetaData();
            for (TableToMybatisVo vo : vos) {
                ResultSet resultSet = metaData.getColumns(connection.getCatalog(), this.schemaName, vo.getTableName(), "%");
                ResultSet primarySet = metaData.getPrimaryKeys(connection.getCatalog(), this.schemaName, vo.getTableName());

                DatabaseEntity entity = getDatabaseEntityFromSet(vo, resultSet, primarySet);
                entityList.add(entity);
            }
        } catch (Exception e) {
            LOGGER.error("数据库实体获取异常,无法提取相关信息...", e);
        } finally {
            JdbcUtil.releaseSqlConnection(connection);
        }
        return entityList;
    }
}
